<template>
  <div>
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="getList"
    >
      <div v-if="projectList.length > 0" style="margin-top: 5px">
        <el-card
          class="box-card"
          shadow="hover"
          v-for="(item, index) in projectList"
          :key="index"
          style="margin: 5px"
        >
          <el-descriptions :title="item.orderName" :column="1" direction="vertical">
            <template slot="extra">
              <!-- <el-button size="small" type="text" @click="toAdd(item)"
                >新增维保记录</el-button
              >
              <el-button size="small" type="text" @click="toDetails(item)"
                >维保记录</el-button
              > -->
              <van-popover
                placement="bottom-end"
                style="float: right; font-size: x-large;"
                v-model="item.flag"
                trigger="click"
                :actions="actions"
                @select="onSelect($event, item)"
                @closed="
                  () => {
                    item.flag = false;
                  }
                "
              >
                <template #reference>
                  <i
                    class="el-icon-more"
                    @click.stop="item.flag = true"
                  ></i>
                </template>
              </van-popover>
            </template>
           <el-descriptions-item label="负责人">
              <label>{{ item.createBy || "--" }}</label>
            </el-descriptions-item>
            <el-descriptions-item label="客户名称">
              <label>{{ item.customerName || "--" }}</label>
            </el-descriptions-item>
            <el-descriptions-item label="运维人员">
              <label>{{ coverUserId(item.opsUserId) || "--" }}</label>
            </el-descriptions-item>
            <el-descriptions-item label="开发人员">
              <label>{{ coverUserId(item.devUserId) || "--" }}</label>
            </el-descriptions-item>
            <el-descriptions-item label="项目进度">
              <label>{{ coverNumber(item) || "--" }}</label>
            </el-descriptions-item>
            <el-descriptions-item label="我的工单">
              <el-button size="small" type="text"  @click="toTaskDetailInfo(item.orderId)">
                <label>{{ item.myTaskCount || "--"}}</label>
              </el-button>
            </el-descriptions-item>
            <el-descriptions-item label="工单金额">
              <label>{{ item.myTaskCount * (!exportInfo ? '0' : exportInfo.externalGrade === '0' ? 30 : 50)}}</label>
            </el-descriptions-item>
            <el-descriptions-item label="备注">
              <label>{{ item.remark || "--" }}</label>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">
              <label>{{ item.createTime || "--" }}</label>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </div>

      <van-empty description="暂无数据" v-else />
    </van-list>
  </div>
</template>

<script>
import { getCrmProjectListByUser } from "@/api/crm/project";

import { getExpertList } from "@/api/crm/expert";

import { getCustomerList } from "@/api/crm/customer";

import { getOrderByCustomerIdAndProgress } from "@/api/crm/order";

import { getExpertByName } from "@/api/crm/expert";

import addWorklog from "../components/pc/addWorklog.vue";
import workLogDetail from "../components/pc/workLogDetail.vue";
export default {
  name: "Project",
  dicts: ["crm_expert_type"],
  components: { addWorklog, workLogDetail },
  props: {
    projectId: {
      type: String,
    },
    queryParams: {
      type: Object,
      default: {
        pageNum: 1,
        pageSize: 10,
        orderId: null,
        userId: null,
        opsUserId: null,
        devUserId: null,
      },
    },
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      finished: false,
      // 总条数
      total: 0,
      // 项目表格数据
      projectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      expertList: [],
      customerList: [],
      orderList: [],
      exportInfo: {},
      actions: [
        { text: "新增维保记录" },
        { text: "查看维保记录" },
      ],
    };
  },
  created() {
    this.$nextTick(() => {
      this.getList();
      this.getExpertList();
      this.getCustomerList();
      this.getExpertByName();
    });
  },
  methods: {
    onSelect(action, item) {
      if (action.text === "新增维保记录") {
        this.toAdd(item)
      } else {
        this.toDetails(item)
      }
    },
    toTaskDetailInfo(orderId){
      // this.$router.push({
      //   path: "/crm/project/components/mobile/taskDetails",
      //   query: {
      //     orderId: orderId,
      //     createBy: this.$store.getters.name,
      //     type: '1'
      //   }
      // })
    },
    coverNumber(row, column, cellValue) {
      row.opsEstimateTaskCount = isNaN(row?.opsEstimateTaskCount) ? 0 : row.opsEstimateTaskCount

      row.devEstimateTaskCount = isNaN(row?.devEstimateTaskCount) ? 0 : row.devEstimateTaskCount

      let count = row.opsEstimateTaskCount + row.devEstimateTaskCount

      const percentage = count === 0 ? 0 : (row.actualTaskCount / count) * 100;
      return Number.isNaN(percentage) || !Number.isFinite(percentage) ? "暂无数据" : `${percentage.toFixed(2)}%`;
    },
    getExpertByName() {
      getExpertByName(this.$store.getters.name).then((res) => {
        this.exportInfo = res.data;
        console.log(this.exportInfo, "dasdsadsad")
      });
    },
    onClickLeft() {
      this.$router.back();
    },
    toAdd(row) {
      this.$router.push({
        path: "/crm/project/components/mobile/addWorkLog",
        query: { projectId: row.projectId },
      });
    },
    toDetails(row) {
      this.$router.push({
        path: "/crm/project/components/mobile/workLogDetails",
        query: { projectId: row.projectId },
      });
    },
    coverUserId(cellValue) {
      if(!cellValue) return '无'
      let userStr = "";
      let arr = cellValue.split(",").map(Number);
      let index = 0;
      arr.forEach((item) => {
        let name = this.expertList.find(
          (expert) => expert.expertId == item
        )?.expertName;

        userStr += index === 0 ? name : "," + name;
        index++;
      });
      return userStr;
    },
    getOrderByCustomerIdAndProgress() {
      getOrderByCustomerIdAndProgress(this.form.customerId).then((res) => {
        this.orderList = res.data;
      });
    },
    getExpertList() {
      getExpertList().then((res) => {
        this.expertList = res.data;
      });
    },
    getCustomerList() {
      getCustomerList().then((res) => {
        this.customerList = res.data;
      });
    },
    /** 查询项目列表 */
    async getList() {
      this.loading = true;
      try {
        let obj = JSON.parse(JSON.stringify(this.queryParams));
        if (this.queryParams.opsUserId) {
          obj.opsUserId = this.queryParams.opsUserId.join(",");
        }
        if (this.queryParams.devUserId) {
          obj.devUserId = this.queryParams.devUserId.join(",");
        }
        let res = await getCrmProjectListByUser(obj);
        // 判断是否加载完所有数据
        if (this.projectList.length >= res.total) {
          this.finished = true;
        } else {
          this.projectList.push(
            ...res.rows.map((item) => ({
              ...item,
              flag: false,
            }))
          );
          this.queryParams.pageNum += 1;
        }
      } catch (error) {
        console.error("加载数据失败", error);
      } finally {
        this.loading = false;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        projectId: null,
        orderId: null,
        userId: null,
        opsUserId: null,
        devUserId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.orderList = [];
      this.projectList = []
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.projectId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "crm/project/export",
        {
          ...this.queryParams,
        },
        `project_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style scoped>
.el-card {
  border-radius: 15px;
}
.el-card label {
  font-size: 15px;
  color: #514848;
}
::v-deep .el-descriptions__title {
  font-size: 20px;
}

::v-deep .el-descriptions__header {
  margin-bottom: 10px;
}
</style>
